/* eslint-disable react/no-unused-state */
import React, { Fragment } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { Form, Button, Input, DatePicker, message, Spin } from 'antd';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import { get as getPath } from 'object-path';
import { BottomAction } from '@/components';
import moment from 'moment';
import { formatMessage } from 'umi';
import { customUpload } from '@/utils/fileUpload';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import OrganizationSelect from '@/components/OrganizationSelect';

import IconFont from '@/components/IconFont';

import FileUpload from '@/components/Custom/FileUpload';

import style from './NoticeDetail.less';

// 不允许添加尺寸大于100M的文件
const myValidateFn = file => {
    if (file.size > 1024 * 1024 * 10) {
        message.error('图片不能大于10M！');
        return false;
    }
    return true;
};
class NoticeAdd extends React.Component {
    constructor(props) {
        super(props);
        const userInfo = JSON.parse(localStorage.getItem('user'));
        this.state = {
            editorState: getPath(this.props, 'value'),
            currentTime: null,
            recvOrganizationCodeTree: [],
            currentUserOrganizationCode: userInfo?.firstOrgInfo?.firstCompanyCode,
            firstCompanyPath: userInfo?.firstOrgInfo?.firstCompanyPath
        };
    }

    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'noticeManage/fetchCompanyTree',
            payload: {
                organizationTypes: [1, 2],
                showTreeFlag: 1,
                parentOrgPathListHasSelf: this.state.firstCompanyPath
            },
            callback: res => {
                if (res.code !== 10000) {
                    message.error(res.msg);
                }
            }
        });
        if (
            getPath(this.props, 'location.query.noticeId') &&
            getPath(this.props, 'location.query.noticeId') !== 'undefined'
        ) {
            this.fetchDetail();
        } else {
            const params = {
                id: null,
                content: null,
                recvOrganizationCode: '',
                startTime: null,
                title: ''
            };
            dispatch({
                type: 'noticeManage/save',
                payload: {
                    changeData: params
                }
            });
        }
    }

    fetchDetail = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'noticeManage/fetchDetail',
            payload: {
                noticeId: getPath(this.props, 'location.query.noticeId')
            },
            callback: res => {
                const { form, noticeManage } = this.props;
                const { changeData } = noticeManage;
                if (res.code === 10000) {
                    const trr = [];
                    if (res.data.recvOrganizationCode && res.data.recvOrganizationCode !== '') {
                        // let theObj = null;
                        res.data.recvOrganizationCode.split(',').forEach(item => {
                            // theObj = {};
                            // theObj.label = res.data.recvOrganizationName.split(',')[index];
                            // theObj.value = item;
                            trr.push(item);
                        });
                    }
                    if (changeData.id) {
                        form.setFieldsValue({
                            content: BraftEditor.createEditorState(`${changeData.content}`)
                        });
                    } else {
                        form.setFieldsValue({
                            content: BraftEditor.createEditorState(null)
                        });
                    }
                    this.setState({
                        recvOrganizationCodeTree: trr
                    });
                } else {
                    message.error(res.msg);
                }
            }
        });
    };

    saveTree = value => {
        this.setState({ recvOrganizationCodeTree: value });
    };

    handleEditorChange = editorState => {
        this.setState({ editorState });
    };

    // 提交表单
    handleSubmit = () => {
        const { form } = this.props;
        form.validateFields((err, values) => {
            if (!err) {
                const { dispatch } = this.props;
                const { currentUserOrganizationCode } = this.state;
                const chooseCompany = [];
                values.recvOrganizationCode.forEach(element => {
                    chooseCompany.push(element);
                });
                const nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
                const formTime = values.startTime.format('YYYY-MM-DD HH:mm:ss');
                const trueTime = moment(nowTime).isBefore(formTime);
                if (!trueTime) {
                    message.error(
                        `${formatMessage({
                            id: 'edit.message.trueTime'
                        })}`
                    );
                    return false;
                }
                const params = {
                    id: values.id ? values.id : null,
                    organizationCode: currentUserOrganizationCode, // 发布人所在机构编码
                    recvOrganizationCode: chooseCompany, // 通知接受机构
                    title: values.title,
                    briefContent: values.content.toText().slice(0, 200), // 简短内容
                    content: values.content.toHTML(),
                    startTime: values.startTime.format('YYYY-MM-DD HH:mm:ss'),
                    attachFile: values?.attachFile?.uploadResourceFile ? [values?.attachFile?.uploadResourceFile] : []
                };
                dispatch({
                    type: values.id ? 'noticeManage/updateNotice' : 'noticeManage/addNotice',
                    payload: params,
                    callback: res => {
                        if (res.code === 10000) {
                            message.success(res.msg);
                            history.push('/office/info/notice');
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
                return true;
            }
            return false;
        });
    };

    handleEndOpenChange = open => {
        const me = this;
        if (open) {
            me.currentTime = moment();
        }
        this.setState({ currentTime: moment() });
    };

    // 不可选择以前的时间
    disabledEndDate = currentDate => {
        const startValue = getPath(this.state, 'currentTime');
        if (!currentDate || !startValue) {
            return false;
        }
        return currentDate.valueOf() <= startValue.valueOf();
    };

    myUploadFn = param => {
        const onSuccess = (response, file) =>
            param.success({
                url: response.data[0].url,
                meta: {
                    id: file.name,
                    title: file.name,
                    alt: file.name
                }
            });
        customUpload({ files: param, onSuccess });
    };

    render() {
        const { loading, noticeManage } = this.props;
        const { changeData } = noticeManage;

        const {
            form: { getFieldDecorator }
        } = this.props;
        const formItemLayout = {
            labelCol: {
                sm: { span: 24 },
                md: { span: 3 }
            },
            wrapperCol: {
                sm: { span: 24 },
                md: { span: 9 }
            }
        };

        const dateFormat = ['YYYY-MM-DD-dddd HH:mm:ss'];
        const controls = [
            'undo',
            'redo',
            'separator',
            'font-size',
            'line-height',
            'letter-spacing',
            'separator',
            'text-color',
            'bold',
            'italic',
            'underline',
            'strike-through',
            'separator',
            'superscript',
            'subscript',
            'remove-styles',
            'emoji',
            'separator',
            'text-indent',
            'text-align',
            'separator',
            'headings',
            'list-ul',
            'list-ol',
            'blockquote',
            'code',
            'separator',
            'media',
            'link',
            'hr',
            'separator',
            'clear'
        ];
        return (
            <Fragment>
                <PageHeaderWrapper>
                    <Spin spinning={loading.models.noticeManage}>
                        <div className={style.wncontainer}>
                            <Form {...formItemLayout} style={{ padding: 16 }}>
                                <Form.Item>
                                    {getFieldDecorator('id', {
                                        initialValue: changeData.id
                                    })(<Input hidden type="number" />)}
                                </Form.Item>
                                <Form.Item
                                    label={formatMessage({
                                        id: 'edit.label.title'
                                    })}
                                    // extra={formatMessage({
                                    //     id: 'edit.message.help'
                                    // })}
                                    // style={{ marginBottom: '10px' }}
                                >
                                    {getFieldDecorator('title', {
                                        initialValue: changeData.title,
                                        rules: [
                                            {
                                                required: true,
                                                message: `${formatMessage({
                                                    id: 'edit.message.title'
                                                })}`
                                            },
                                            {
                                                min: 2,
                                                max: 50,
                                                message: '请输入2-50个字符'
                                            }
                                        ]
                                    })(
                                        <Input
                                            placeholder={formatMessage({
                                                id: 'edit.message.title'
                                            })}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item
                                    label={formatMessage({
                                        id: 'edit.label.startTime'
                                    })}
                                >
                                    {getFieldDecorator('startTime', {
                                        initialValue: changeData.startTime
                                            ? moment(changeData.startTime, dateFormat)
                                            : null,
                                        rules: [
                                            {
                                                required: true,
                                                message: `${formatMessage({
                                                    id: 'edit.message.startTime'
                                                })}`
                                            }
                                        ]
                                    })(
                                        <DatePicker
                                            showTime={{
                                                defaultValue: moment(
                                                    moment()
                                                        .add(2, 'minutes')
                                                        .format('HH:mm:ss'),
                                                    'HH:mm:ss'
                                                )
                                            }}
                                            showToday={false}
                                            placeholder={formatMessage({
                                                id: 'edit.message.startTime'
                                            })}
                                            format="YYYY-MM-DD HH:mm:ss"
                                            disabledDate={this.disabledEndDate}
                                            onOpenChange={this.handleEndOpenChange}
                                            getCalendarContainer={trigger => trigger.parentNode}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item
                                    label={formatMessage({
                                        id: 'edit.label.uploadFile'
                                    })}
                                >
                                    {getFieldDecorator('attachFile', {
                                        initialValue: {
                                            allFileList:
                                                changeData?.noticeFile?.map(item => ({
                                                    ...item,
                                                    uid: item.keyName,
                                                    name: item.originName
                                                })) || [],
                                            uploadResourceFile: null
                                        }
                                    })(
                                        <FileUpload
                                            checkFileSize={50}
                                            checkFileSizeMsg="文件大小不能超过50MB！"
                                            checkFileType="rar,zip,pdf,jpg,jpeg,png,doc,docx,xls,xlsx"
                                            checkFileTypeMsg="只能上传rar,zip,pdf,jpg,jpeg,png,doc,docx,xls,xlsx格式的文件！"
                                            categoryCode="noticeFile"
                                        >
                                            <Button>
                                                <IconFont type="upload" />
                                                上传文件
                                            </Button>
                                        </FileUpload>
                                    )}
                                    <div className={style.fileTxt}>
                                        支持rar,zip,pdf,jpg,jpeg,png,doc,docx,xls,xlsx格式的文件上传，大小为50M以内的文件。
                                    </div>
                                </Form.Item>
                                <Form.Item
                                    label={formatMessage({
                                        id: 'edit.label.recvOrganizationCode'
                                    })}
                                >
                                    {getFieldDecorator('recvOrganizationCode', {
                                        initialValue: getPath(this.state, 'recvOrganizationCodeTree'),
                                        rules: [
                                            {
                                                required: true,
                                                message: `${formatMessage({
                                                    id: 'edit.message.recvOrganizationCode'
                                                })}`
                                            }
                                        ]
                                    })(
                                        <OrganizationSelect
                                            isStrictly
                                            treeCheckable
                                            style={{ width: '100%' }}
                                            isNeedPermission
                                            unLoading
                                            extraQuery={{ parentOrgPathListHasSelf: this.state.firstCompanyPath }}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item
                                    className={style.noticeTextAdd}
                                    label={formatMessage({
                                        id: 'edit.label.content'
                                    })}
                                    wrapperCol={{ md: { span: 16 } }}
                                >
                                    {getFieldDecorator('content', {
                                        rules: [
                                            {
                                                required: true,
                                                message: `${formatMessage({
                                                    id: 'edit.message.noticecontent'
                                                })}`,
                                                validator: (_, value, callback) => {
                                                    if (!value || value.isEmpty()) {
                                                        callback(
                                                            `${formatMessage({
                                                                id: 'edit.message.noticecontent'
                                                            })}`
                                                        );
                                                    } else {
                                                        callback();
                                                    }
                                                }
                                            }
                                        ]
                                    })(
                                        <BraftEditor
                                            onChange={this.handleEditorChange}
                                            media={{
                                                uploadFn: this.myUploadFn,
                                                validateFn: myValidateFn,
                                                onChange: this.fileChange,
                                                accepts: {
                                                    image: 'image/png,image/jpeg,image/gif'
                                                }
                                            }}
                                            controls={controls}
                                            excludeControls={['fullscreen']}
                                            imageControls={[
                                                {
                                                    onClick: block => {
                                                        console.log(block);
                                                    } // 指定控件点击后的回调，参数为当前图片的block对象
                                                },
                                                'align-left',
                                                'align-center',
                                                'align-right',
                                                'size',
                                                'remove'
                                            ]}
                                            style={{
                                                border: '1px solid #d9d9d9',
                                                borderTopWidth: '1.02px',
                                                borderRadius: '4px',
                                                marginTop: '4px'
                                            }}
                                            className={style.paddingBraftEditor}
                                        />
                                    )}
                                </Form.Item>
                                <BottomAction>
                                    <Button
                                        type="primary"
                                        disabled={loading.models.noticeManage}
                                        style={{ marginRight: 16 }}
                                        onClick={this.handleSubmit}
                                    >
                                        {formatMessage({
                                            id: 'btn.form.submit'
                                        })}
                                    </Button>
                                    <Button onClick={() => history.push('/office/info/notice')}>
                                        {formatMessage({
                                            id: 'btn.form.unsubmit'
                                        })}
                                    </Button>
                                </BottomAction>
                            </Form>
                        </div>
                    </Spin>
                </PageHeaderWrapper>
            </Fragment>
        );
    }
}
export default withRoutePage(
    connect(({ noticeManage, loading }) => ({
        noticeManage,
        loading
    }))(Form.create()(NoticeAdd))
);
